<?php
include 'includes/functions.php';
echo db_connect();
   
$section_id = $_POST['section_id'];
$section_num = $_POST['section_num']; //echo"|$section_num|";
$chapter_id = $_POST['chapter_id'];  
$title = $_POST['form_title'];

if($chapter_id=='new' || $section_id=='new') {
	if ($chapter_id != "" && !$section_id) { 
		$max = mysql_query("SELECT MAX(`order`) FROM documentation_chapters"); $max_row=mysql_fetch_array($max); $next = $max_row[0] +1;
		$sql = "INSERT INTO documentation_chapters (title,`order`) VALUES ('$title', '$next')";  
	} elseif ($section_id) { 
			$next = 1;
			$max = mysql_query("SELECT MAX(`section_num`) FROM documentation_sections WHERE documentation_chapter_id = '$chapter_id'");
			if ($max_row=mysql_fetch_array($max)) { $next = $max_row[0] +1; }else { DIE ('max error'); } 
			$sql = "INSERT INTO documentation_sections (documentation_chapter_id,title,section_num,modified_ts) VALUES ('$chapter_id','$title', '$next',NOW())"; 
		} 
 
	
} else {

	if ($chapter_id != "") { $sql = "UPDATE documentation_chapters SET `title` = '$title' WHERE documentation_chapter_id = '$chapter_id'";  }
	if ($section_id) { $sql = "UPDATE documentation_sections SET `title` = '$title',modified_ts = NOW() WHERE section_id = '$section_id'";  $update_name=1;  } 
}
if (!mysql_query($sql)) { echo "error".mysql_error().$sql; }else{ echo mysql_insert_id();}

if ($update_name) {
 // when renaming a secition, we have to change the 'title' field for ALL records for that section, because of this semi-flat format  
 $mms = mysql_query("SELECT documentation_chapter_id FROM documentation_sections WHERE section_id = '$section_id'"); 
 $mms_row = mysql_fetch_array($mms); $chid = $mms_row[0];  
 if (!mysql_query("UPDATE documentation_sections SET title = '$title' WHERE documentation_chapter_id = '$chid' AND section_num = '$section_num'")) echo "problem"; 
	
}    

?>